{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9e34586b",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/agent/openai_agent_context_retrieval.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "99cea58c-48bc-4af6-8358-df9695659983",
   "metadata": {},
   "source": [
    "# Context-Augmented OpenAI Agent"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "673df1fe-eb6c-46ea-9a73-a96e7ae7942e",
   "metadata": {},
   "source": [
    "In this tutorial, we show you how to use our `ContextRetrieverOpenAIAgent` implementation\n",
    "to build an agent on top of OpenAI's function API and store/index an arbitrary number of tools. Our indexing/retrieval modules help to remove the complexity of having too many functions to fit in the prompt."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "54b7bc2e-606f-411a-9490-fcfab9236dfc",
   "metadata": {},
   "source": [
    "## Initial Setup "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "23e80e5b-aaee-4f23-b338-7ae62b08141f",
   "metadata": {},
   "source": [
    "Here we setup a ContextRetrieverOpenAIAgent. This agent will perform retrieval first before calling any tools. This can help ground the agent's tool picking and answering capabilities in context."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d6d2e0ae",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c40cadb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-agent-openai-legacy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21770827",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d47283b-025e-4874-88ed-76245b22f82e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from typing import Sequence\n",
    "\n",
    "from llama_index.core import (\n",
    "    SimpleDirectoryReader,\n",
    "    VectorStoreIndex,\n",
    "    StorageContext,\n",
    "    load_index_from_storage,\n",
    ")\n",
    "from llama_index.core.tools import QueryEngineTool, ToolMetadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f034df0-f6f1-4ffb-9c4b-d68c2202051c",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    storage_context = StorageContext.from_defaults(\n",
    "        persist_dir=\"./storage/march\"\n",
    "    )\n",
    "    march_index = load_index_from_storage(storage_context)\n",
    "\n",
    "    storage_context = StorageContext.from_defaults(\n",
    "        persist_dir=\"./storage/june\"\n",
    "    )\n",
    "    june_index = load_index_from_storage(storage_context)\n",
    "\n",
    "    storage_context = StorageContext.from_defaults(\n",
    "        persist_dir=\"./storage/sept\"\n",
    "    )\n",
    "    sept_index = load_index_from_storage(storage_context)\n",
    "\n",
    "    index_loaded = True\n",
    "except:\n",
    "    index_loaded = False"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f9010d88",
   "metadata": {},
   "source": [
    "Download Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75aa7b79",
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p 'data/10q/'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_march_2022.pdf' -O 'data/10q/uber_10q_march_2022.pdf'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_june_2022.pdf' -O 'data/10q/uber_10q_june_2022.pdf'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_sept_2022.pdf' -O 'data/10q/uber_10q_sept_2022.pdf'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a90e4d4-589b-4349-a134-a2ef931d8e89",
   "metadata": {},
   "outputs": [],
   "source": [
    "# build indexes across the three data sources\n",
    "\n",
    "if not index_loaded:\n",
    "    # load data\n",
    "    march_docs = SimpleDirectoryReader(\n",
    "        input_files=[\"./data/10q/uber_10q_march_2022.pdf\"]\n",
    "    ).load_data()\n",
    "    june_docs = SimpleDirectoryReader(\n",
    "        input_files=[\"./data/10q/uber_10q_june_2022.pdf\"]\n",
    "    ).load_data()\n",
    "    sept_docs = SimpleDirectoryReader(\n",
    "        input_files=[\"./data/10q/uber_10q_sept_2022.pdf\"]\n",
    "    ).load_data()\n",
    "\n",
    "    # build index\n",
    "    march_index = VectorStoreIndex.from_documents(march_docs)\n",
    "    june_index = VectorStoreIndex.from_documents(june_docs)\n",
    "    sept_index = VectorStoreIndex.from_documents(sept_docs)\n",
    "\n",
    "    # persist index\n",
    "    march_index.storage_context.persist(persist_dir=\"./storage/march\")\n",
    "    june_index.storage_context.persist(persist_dir=\"./storage/june\")\n",
    "    sept_index.storage_context.persist(persist_dir=\"./storage/sept\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00f82f26-83a6-4a37-8a9f-55bf49d8b247",
   "metadata": {},
   "outputs": [],
   "source": [
    "march_engine = march_index.as_query_engine(similarity_top_k=3)\n",
    "june_engine = june_index.as_query_engine(similarity_top_k=3)\n",
    "sept_engine = sept_index.as_query_engine(similarity_top_k=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1edb4379-75b8-4b83-8a2d-16170fa6cb67",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine_tools = [\n",
    "    QueryEngineTool(\n",
    "        query_engine=march_engine,\n",
    "        metadata=ToolMetadata(\n",
    "            name=\"uber_march_10q\",\n",
    "            description=(\n",
    "                \"Provides information about Uber 10Q filings for March 2022. \"\n",
    "                \"Use a detailed plain text question as input to the tool.\"\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    QueryEngineTool(\n",
    "        query_engine=june_engine,\n",
    "        metadata=ToolMetadata(\n",
    "            name=\"uber_june_10q\",\n",
    "            description=(\n",
    "                \"Provides information about Uber financials for June 2021. \"\n",
    "                \"Use a detailed plain text question as input to the tool.\"\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    QueryEngineTool(\n",
    "        query_engine=sept_engine,\n",
    "        metadata=ToolMetadata(\n",
    "            name=\"uber_sept_10q\",\n",
    "            description=(\n",
    "                \"Provides information about Uber financials for Sept 2021. \"\n",
    "                \"Use a detailed plain text question as input to the tool.\"\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b08efb96-ce44-4706-a22d-b0c670b23a60",
   "metadata": {},
   "source": [
    "### Try Context-Augmented Agent\n",
    "\n",
    "Here we augment our agent with context in different settings:\n",
    "- toy context: we define some abbreviations that map to financial terms (e.g. R=Revenue). We supply this as context to the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72709da5-785e-4b9d-9e8f-231a2d2fbb53",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import Document\n",
    "from llama_index.agent.openai_legacy import ContextRetrieverOpenAIAgent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2b235ed-d2a0-46cb-830b-d1a3affeb0c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# toy index - stores a list of abbreviations\n",
    "texts = [\n",
    "    \"Abbreviation: X = Revenue\",\n",
    "    \"Abbreviation: YZ = Risk Factors\",\n",
    "    \"Abbreviation: Z = Costs\",\n",
    "]\n",
    "docs = [Document(text=t) for t in texts]\n",
    "context_index = VectorStoreIndex.from_documents(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b58bac2-dbc2-40b2-a29e-f96c02ef5396",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_agent = ContextRetrieverOpenAIAgent.from_tools_and_retriever(\n",
    "    query_engine_tools,\n",
    "    context_index.as_retriever(similarity_top_k=1),\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b44e9819-69a5-4085-9957-27d8eb940d24",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33;1m\u001b[1;3mContext information is below.\n",
      "---------------------\n",
      "Abbreviation: YZ = Risk Factors\n",
      "---------------------\n",
      "Given the context information and not prior knowledge, either pick the corresponding tool or answer the function: What is the YZ of March 2022?\n",
      "\n",
      "\u001b[0m=== Calling Function ===\n",
      "Calling function: uber_march_10q with args: {\n",
      "  \"input\": \"Risk Factors\"\n",
      "}\n",
      "Got output: \n",
      "•The COVID-19 pandemic and the impact of actions to mitigate the pandemic have adversely affected and may continue to adversely affect parts of our business.\n",
      "•Our business would be adversely affected if Drivers were classified as employees, workers or quasi-employees instead of independent contractors.\n",
      "•The mobility, delivery, and logistics industries are highly competitive, with well-established and low-cost alternatives that have been available for decades, low barriers to entry, low switching costs, and well-capitalized competitors in nearly every major geographic region.\n",
      "•To remain competitive in certain markets, we have in the past lowered, and may continue to lower, fares or service fees, and we have in the past offered, and may continue to offer, significant Driver incentives and consumer discounts and promotions.\n",
      "•We have incurred significant losses since inception, including in the United States and other major markets. We expect our operating expenses to increase significantly in the foreseeable future, and we may not achieve or maintain profitability.\n",
      "•If we are unable to attract or maintain a critical mass of Drivers, consumers, merchants, shippers, and carriers, whether as a result of competition or other factors, our platform will become less appealing to platform users.\n",
      "•Maintaining and enhancing our brand and reputation is critical to our business prospects. We have previously received significant media coverage and negative publicity regarding our brand and reputation, and while we have taken significant steps to rehabilitate our brand and reputation, failure to maintain and enhance our brand and reputation could adversely affect our business.\n",
      "•The impact of economic conditions, including the resulting effect on discretionary consumer spending, may harm our business and operating results.\n",
      "•Increases in fuel, food, labor, energy, and other costs due to inflation and other factors could adversely affect our operating results.\n",
      "•If we experience security or privacy breaches or other unauthorized or improper access to, use of, disclosure of, alteration of or destruction of our proprietary or confidential data, employee data, or platform user data.\n",
      "•Cyberattacks, including computer malware, ransomware, viruses, spamming, and phishing attacks could harm our reputation, business, and operating results.\n",
      "•We are subject to climate change risks, including physical and transitional risks, and if we are unable to manage such risks, our business may be adversely impacted.\n",
      "•We have made climate related commitments that require us to invest significant effort, resources, and management time and circumstances may arise, including those beyond our control, that may require us to revise the contemplated timeframes for implementing these commitments.\n",
      "•We rely on third parties maintaining open marketplaces to distribute our platform and to provide the software we use in certain of our products and offerings. If such third parties interfere with the distribution of our products or offerings or with our use of such software, our business would be adversely affected.\n",
      "•We will require additional capital to support the growth of our business, and this capital might not be available on reasonable terms or at all.\n",
      "•If we are unable to successfully identify, acquire and integrate suitable businesses, our operating results and prospects could be harmed, and any businesses we acquire may not perform as expected or be effectively integrated.\n",
      "•We may continue to be blocked from or limited in providing or operating our products and offerings in certain jurisdictions, and may be required to modify our business model in those jurisdictions as a result.\n",
      "•Our business is subject to numerous legal and regulatory risks that could have an adverse impact on our business and future prospects.\n",
      "•Our business is subject to extensive government regulation and oversight relating to the provision of payment and financial services.\n",
      "•We face risks related to our collection, use, transfer, disclosure, and other processing of data, which could result in investigations, inquiries, litigation, fines, legislative and regulatory action, and negative press about our privacy and data protection practices.\n",
      "•If we are unable to protect our intellectual property, or if third parties are successful in claiming that we are misappropriating the intellectual property of others, we may incur significant expense and our business may be adversely affected.\n",
      "•The market price of our common stock has been, and may continue to be, volatile or may decline steeply or suddenly regardless of our operating performance, and we may not be able to meet investor or analyst expectations. You may not be able to resell your shares at or above the price you paid and may lose all or part of your investment.\n",
      "========================\n"
     ]
    }
   ],
   "source": [
    "response = context_agent.chat(\"What is the YZ of March 2022?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9969fceb-d9b2-491f-92f2-d5e0fe5a8ed2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The risk factors for Uber in March 2022 include:\n",
      "\n",
      "1. The adverse impact of the COVID-19 pandemic and actions taken to mitigate it on Uber's business.\n",
      "2. The potential adverse effect on Uber's business if drivers are classified as employees instead of independent contractors.\n",
      "3. Intense competition in the mobility, delivery, and logistics industries, with low-cost alternatives and well-capitalized competitors.\n",
      "4. The need to lower fares, offer driver incentives, and provide consumer discounts and promotions to remain competitive in certain markets.\n",
      "5. Uber's history of significant losses and the expectation of increased operating expenses in the future, which may affect profitability.\n",
      "6. The importance of attracting and maintaining a critical mass of drivers, consumers, merchants, shippers, and carriers to keep the platform appealing.\n",
      "7. The significance of maintaining and enhancing Uber's brand and reputation, as negative publicity could harm the business.\n",
      "8. The potential impact of economic conditions and discretionary consumer spending on Uber's business.\n",
      "9. The adverse effect of increasing costs, such as fuel, food, labor, energy, and inflation, on Uber's operating results.\n",
      "10. The risk of security or privacy breaches and unauthorized access to Uber's proprietary or confidential data.\n",
      "11. The potential harm to Uber's reputation, business, and operating results from cyberattacks.\n",
      "12. The impact of climate change risks, including physical and transitional risks, on Uber's business.\n",
      "13. The commitment to climate-related initiatives that require significant effort, resources, and management time.\n",
      "14. The reliance on third parties for distributing Uber's platform and providing software, with the risk of interference or limitations.\n",
      "15. The need for additional capital to support Uber's business growth, with uncertainty about its availability on reasonable terms.\n",
      "16. The risks associated with identifying, acquiring, and integrating suitable businesses.\n",
      "17. The potential limitations and modifications to Uber's business model in certain jurisdictions.\n",
      "18. The legal and regulatory risks that could adversely impact Uber's business and future prospects.\n",
      "19. The extensive government regulation and oversight related to payment and financial services provided by Uber.\n",
      "20. The risks associated with data collection, use, transfer, disclosure, and processing, including investigations, litigation, and fines.\n",
      "21. The importance of protecting Uber's intellectual property and the risk of claims of misappropriation.\n",
      "22. The volatility and potential decline in the market price of Uber's common stock, which may not reflect operating performance.\n",
      "\n",
      "Please note that this is a summary of the risk factors mentioned in Uber's March 2022 10Q filing. For more detailed information, please refer to the official filing.\n"
     ]
    }
   ],
   "source": [
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c407dd42-39a3-4bda-8294-27ac043a5adb",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_agent.chat(\"What is the X and Z in September 2022?\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ad81c4e1-4ecb-405d-bb03-a4c3549816e7",
   "metadata": {},
   "source": [
    "### Use Uber 10-Q as context, use Calculator as Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8dc898e-5fe0-45a2-8e04-debdaeb2c1bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.tools import BaseTool, FunctionTool\n",
    "\n",
    "\n",
    "def magic_formula(revenue: int, cost: int) -> int:\n",
    "    \"\"\"Runs MAGIC_FORMULA on revenue and cost.\"\"\"\n",
    "    return revenue - cost\n",
    "\n",
    "\n",
    "magic_tool = FunctionTool.from_defaults(fn=magic_formula, name=\"magic_formula\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4dc2e5b7-3b41-43ea-91db-847cf28fc6a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_agent = ContextRetrieverOpenAIAgent.from_tools_and_retriever(\n",
    "    [magic_tool], sept_index.as_retriever(similarity_top_k=3), verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99b9a0f8-0029-495c-a44b-913d1e0556e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33;1m\u001b[1;3mContext information is below.\n",
      "---------------------\n",
      "Three Months Ended September 30, Nine Months Ended September 30,\n",
      "2021 2022 2021 2022\n",
      "Revenue 100 % 100 % 100 % 100 %\n",
      "Costs and expenses\n",
      "Cost of revenue, exclusive of depreciation and amortization shown separately\n",
      "below 50 % 62 % 53 % 62 %\n",
      "Operations and support 10 % 7 % 11 % 8 %\n",
      "Sales and marketing 24 % 14 % 30 % 16 %\n",
      "Research and development 10 % 9 % 13 % 9 %\n",
      "General and administrative 13 % 11 % 15 % 10 %\n",
      "Depreciation and amortization 4 % 3 % 6 % 3 %\n",
      "Total costs and expenses 112 % 106 % 128 % 107 %\n",
      "Loss from operations (12)% (6)% (28)% (7)%\n",
      "Interest expense (3)% (2)% (3)% (2)%\n",
      "Other income (expense), net (38)% (6)% 16 % (34)%\n",
      "Loss before income taxes and income (loss) from equity method\n",
      "investments (52)% (14)% (16)% (43)%\n",
      "Provision for (benefit from) income taxes (2)% 1 % (3)% — %\n",
      "Income (loss) from equity method investments — % — % — % — %\n",
      "Net loss including non-controlling interests (50)% (14)% (12)% (42)%\n",
      "Less: net income (loss) attributable to non-controlling interests,\n",
      "net of tax — % — % (1)% — %\n",
      "Net loss attributable to Uber Technologies, Inc. (50)% (14)% (12)% (42)%\n",
      " Totals of percentage of revenues may not foot due to rounding.\n",
      "The following discussion and analysis is for the three and nine months ended September 30, 2022 compared to same period in 2021.\n",
      "Revenue\n",
      "Three Months Ended September 30, Nine Months Ended September 30,\n",
      "(In millions, except per centages) 2021 2022 % Change 2021 2022 % Change\n",
      "Revenue $ 4,845 $ 8,343 72 %$ 11,677 $ 23,270 99 %\n",
      "Three Months Ended September 30, 2022 Compared with the Same Period in 2021\n",
      "Revenue increased $3.5 billion, or 72%, primarily attributable to an increase in Gross Bookings of 26%, or 32% on a constant currency basis. The increase in\n",
      "Gross Bookings was primarily driven by increases in Mobility Trip volumes as the business recovers from the impacts of COVID-19 and a $1.3 billion increase in\n",
      "Freight Gross Bookings resulting primarily from the acquisition of Transplace in the fourth quarter of 2021. Additionally, during the third quarter of 2022, we saw a\n",
      "$1.1 billion increase in Mobility revenue as a result of business model changes in the UK. We also saw a $164 million increase in Delivery revenue resulting from\n",
      "an increase in certain Courier payments and incentives that are recorded in cost of revenue, exclusive of depreciation and amortization, for certain markets where\n",
      "we are primarily responsible for Delivery services and pay Couriers for services provided.\n",
      "Nine Months Ended September 30, 2022 Compared with the Same Period in 2021\n",
      "Revenue increased $11.6 billion, or 99%, primarily attributable to an increase in Gross Bookings of 31%, or 36% on a constant currency basis. The increase in\n",
      "Gross Bookings was primarily driven by increases in Mobility Trip volumes as the business recovers from the impacts of COVID-19 and a $4.4 billion increase in\n",
      "Freight Gross Bookings resulting primarily from the acquisition of Transplace in the fourth quarter of 2021. Additionally, during the first nine months of 2022, we\n",
      "saw a $2.2 billion net increase in Mobility revenue as a result of business model changes in the UK and an accrual made for the resolution of historical claims in\n",
      "the UK relating to the classification of drivers. We also saw a $751 million increase in Delivery revenue resulting from an increase in certain Courier payments and\n",
      "incentives that are recorded in cost of revenue, exclusive of depreciation and amortization, for certain markets where we are primarily responsible for\n",
      "UBER TECHNOLOGIES, INC.\n",
      "CONDENSED CONSOLIDATED STATEMENTS OF OPERATIONS\n",
      "(In millions, except share amounts which are reflected in thousands, and per share amounts)\n",
      "(Unaudited)\n",
      "Three Months Ended September  30, Nine Months Ended September  30,\n",
      "2021 2022 2021 2022\n",
      "Revenue $ 4,845 $ 8,343 $ 11,677 $ 23,270 \n",
      "Costs and expenses\n",
      "Cost of revenue, exclusive of depreciation and amortization shown separately\n",
      "below 2,438 5,173 6,247 14,352 \n",
      "Operations and support 475 617 1,330 1,808 \n",
      "Sales and marketing 1,168 1,153 3,527 3,634 \n",
      "Research and development 493 760 1,496 2,051 \n",
      "General and administrative 625 908 1,705 2,391 \n",
      "Depreciation and amortization 218 227 656 724 \n",
      "Total costs and expenses 5,417 8,838 14,961 24,960 \n",
      "Loss from operations (572) (495) (3,284) (1,690)\n",
      "Interest expense (123) (146) (353) (414)\n",
      "Other income (expense), net (1,832) (535) 1,821 (7,796)\n",
      "Loss before income taxes and income (loss) from equity method investments (2,527) (1,176) (1,816) (9,900)\n",
      "Provision for (benefit from) income taxes (101) 58 (395) (97)\n",
      "Income (loss) from equity method investments (13) 30 (28) 65 \n",
      "Net loss including non-controlling interests (2,439) (1,204) (1,449) (9,738)\n",
      "Less: net income (loss) attributable to non-controlling interests, net of\n",
      "tax (15) 2 (61) (2)\n",
      "Net loss attributable to Uber Technologies, Inc. $ (2,424)$ (1,206)$ (1,388)$ (9,736)\n",
      "Net loss per share attributable to Uber Technologies, Inc. common\n",
      "stockholders:\n",
      "Basic $ (1.28)$ (0.61)$ (0.74)$ (4.96)\n",
      "Diluted $ (1.28)$ (0.61)$ (0.75)$ (4.97)\n",
      "Weighted-average shares used to compute net loss per share attributable to\n",
      "common stockholders:\n",
      "Basic 1,898,954 1,979,299 1,877,655 1,964,483 \n",
      "Diluted 1,898,954 1,979,299 1,878,997 1,968,228 \n",
      "The accompanying notes are an integral part of these condensed consolidated financial statements.\n",
      "5\n",
      "Components of Results of Operations\n",
      "Revenue\n",
      "We generate substantially all of our revenue from fees paid by Drivers and Merchants for use of our platform. We have concluded that we are an agent in these\n",
      "arrangements as we arrange for other parties to provide the service to the end-user. Under this model, revenue is net of Driver and Merchant earnings and Driver\n",
      "incentives. We act as an agent in these transactions by connecting consumers to Drivers and Merchants to facilitate a Trip, meal or grocery delivery service.\n",
      "During the first quarter of 2022, we modified our arrangements in certain markets and, as a result, concluded we are responsible for the provision of mobility\n",
      "services to end-users in those markets. We have determined that in these transactions, end-users are our customers and our sole performance obligation in the\n",
      "transaction is to provide transportation services to the end-user. We recognize revenue when a trip is complete. In these markets where we are responsible for\n",
      "mobility services, we present revenue from end-users on a gross basis, as we control the service provided by Drivers to end-users, while payments to Drivers in\n",
      "exchange for mobility services are recognized in cost of revenue, exclusive of depreciation and amortization.\n",
      "For additional discussion related to our revenue, see the section titled “Management’s Discussion and Analysis of Financial Condition and Results of\n",
      "Operations - Critical Accounting Estimates - Revenue Recognition,” “Note 1 - Description of Business and Summary of Significant Accounting Policies - Revenue\n",
      "Recognition,” and “Note 2 - Revenue” to our audited consolidated financial statements included in our Annual Report Form 10-K for the year ended December 31,\n",
      "2021 and Note 2 – Revenue in this Quarterly Report on Form 10-Q.\n",
      "Cost of Revenue, Exclusive of Depreciation and Amortization\n",
      "Cost of revenue, exclusive of depreciation and amortization, primarily consists of certain insurance costs related to our Mobility and Delivery offerings, credit\n",
      "card processing fees, bank fees, data center and networking expenses, mobile device and service costs, costs incurred with Carriers for Uber Freight transportation\n",
      "services, amounts related to fare chargebacks and other credit card losses as well as costs incurred for certain Mobility and Delivery transactions where we are\n",
      "primarily responsible for mobility or delivery services and pay Drivers and Couriers for services.\n",
      "We expect that cost of revenue, exclusive of depreciation and amortization, will fluctuate on an absolute dollar basis for the foreseeable future in line with Trip\n",
      "volume changes on the platform. As Trips increase or decrease, we expect related changes for insurance costs, credit card processing fees, hosting and co-located\n",
      "data center expenses, maps license fees, and other cost of revenue, exclusive of depreciation and amortization.\n",
      "Operations and Support\n",
      "Operations and support expenses primarily consist of compensation expenses, including stock-based compensation, for employees that support operations in\n",
      "cities, including the general managers, Driver operations, platform user support representatives and community managers. Also included is the cost of customer\n",
      "support, Driver background checks and the allocation of certain corporate costs.\n",
      "As our business recovers from the impacts of COVID-19 and Trip volume increases, we would expect operations and support expenses to increase on an\n",
      "absolute dollar basis for the foreseeable future, but decrease as a percentage of revenue as we become more efficient in supporting platform users.\n",
      "Sales and Marketing\n",
      "Sales and marketing expenses primarily consist of compensation costs, including stock-based compensation to sales and marketing employees, advertising\n",
      "costs, product marketing costs and discounts, loyalty programs, promotions, refunds, and credits provided to end-users who are not customers, and the allocation of\n",
      "certain corporate costs. We expense advertising and other promotional expenditures as incurred.\n",
      "As our business recovers from the impacts of COVID-19, we would anticipate sales and marketing expenses to increase on an absolute dollar basis for\n",
      "---------------------\n",
      "Given the context information and not prior knowledge, either pick the corresponding tool or answer the function: Can you run MAGIC_FORMULA on Uber's revenue and cost?\n",
      "\n",
      "\u001b[0m=== Calling Function ===\n",
      "Calling function: magic_formula with args: {\n",
      "  \"revenue\": 23270,\n",
      "  \"cost\": 24960\n",
      "}\n",
      "Got output: -1690\n",
      "========================\n"
     ]
    }
   ],
   "source": [
    "response = context_agent.chat(\n",
    "    \"Can you run MAGIC_FORMULA on Uber's revenue and cost?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9830d9d8-ea62-4c23-af3a-e2fdd46d90d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The result of running MAGIC_FORMULA on Uber's revenue and cost is -1690.\n"
     ]
    }
   ],
   "source": [
    "print(response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_index_v2",
   "language": "python",
   "name": "llama_index_v2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
